package drds.server.util;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NameThreadFactory implements ThreadFactory {
	private final ThreadGroup threadGroup;
	private final String namePrefix;
	private final AtomicInteger threadId;
	private final boolean isDaemon;

	public NameThreadFactory(String namePrefix, boolean isDaemon) {
		SecurityManager securityManager = System.getSecurityManager();
		this.threadGroup = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
		this.namePrefix = namePrefix;
		this.threadId = new AtomicInteger(0);
		this.isDaemon = isDaemon;
	}

	public Thread newThread(Runnable runnable) {
		Thread thread = new Thread(threadGroup, runnable, namePrefix + threadId.getAndIncrement());
		thread.setDaemon(isDaemon);
		return thread;
	}
}
